package com.example.demo.atomic;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

public class AtomicStampedReferenceTest {

    private static AtomicInteger index = new AtomicInteger(10);

    private static AtomicStampedReference<Integer> stampedReference = new AtomicStampedReference<>(10, 1);

    public static void main(String[] args) {
        new Thread(() -> {
            int stamp = stampedReference.getStamp();
            System.out.println(Thread.currentThread().getName() + " 第1次版本号：" + stamp);
            stampedReference.compareAndSet(10, 11,
                    stampedReference.getStamp(), stampedReference.getStamp() + 1);
            System.out.println(Thread.currentThread().getName() + " 第2次版本号："
                    + stampedReference.getStamp());
            stampedReference.compareAndSet(11, 10,
                    stampedReference.getStamp(), stampedReference.getStamp() + 1);
            System.out.println(Thread.currentThread().getName() + " 第3次版本号："
                    + stampedReference.getStamp());
        }, "张三").start();
        new Thread(() -> {
            try {
                int stamp = stampedReference.getStamp();
                System.out.println(Thread.currentThread().getName() + " 第1次版本号：" + stamp);
                TimeUnit.SECONDS.sleep(2);
                boolean isSuccess = stampedReference.compareAndSet(10, 12,
                        stampedReference.getStamp(), stampedReference.getStamp() + 1);
                System.out.println(Thread.currentThread().getName() + " 是否修改成功：" + isSuccess
                        + " 当前版本" + stampedReference.getStamp());
                System.out.println(Thread.currentThread().getName() + " 当前实际值："
                        + stampedReference.getReference());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "李四").start();
    }
}
